package com.caosy.grassthinkremote.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity//启用Spring Security支持，同时告诉Spring Boot这事一个配置类
//WebSecurityConfigurerAdapter 是一个抽象类，提供了默认的安全配置。通过继承这个类，我们可以自定义安全配置
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置HTTP安全规则
        http.csrf().disable()//禁用csrf
                .authorizeRequests()//开始配置URL访问权限
                .antMatchers("/user/auth","/html/**").permitAll()//允许所有用户范文/auth这个接口
                .anyRequest().authenticated()//其他请求都需要认证
                .and()
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);//添加过滤器
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();//强密码加密算法，用于加密和验证用户名密码
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }
}
